#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Vergil
# datetime:2019/3/6 0:02
# software: PyCharm
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django import forms, VERSION as django_version
from django.db import router
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django.contrib.admin.utils import get_deleted_objects
from django.utils.translation import ugettext as _, ungettext

from xadmin.plugins.actions import BaseActionView
from django.shortcuts import HttpResponse

from xadmin.util import model_ngettext
from xadmin.views.base import filter_hook

from notifications.signals import notify

from user.models import User

ACTION_CHECKBOX_NAME = '_selected_action'
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)

class CertificationAction(BaseActionView):
    action_name = "certification_action"
    description = '通过认证'
    model_perm = 'delete'

    delete_confirmation_template = None
    delete_selected_confirmation_template = None

    delete_models_batch = True

    icon = 'fa fa-check-square-o'

    @filter_hook
    def delete_models(self, queryset):
        n = queryset.count()
        if n:
            admin = User.objects.get(is_superuser=1)
            for obj in queryset:
                user_id = obj.user.id
                user = User.objects.get(id=user_id)
                real_name, id_card = obj.real_name, obj.id_card

                # 更新该用户基本信息
                User.objects.filter(id=user_id).update(is_auth=1, real_name=real_name, id_card=id_card)

                obj.delete()
                # 将用户归入实名用户组,可享受音乐下载权限
                group = Group.objects.filter(name='实名用户组')
                if group:
                    user.groups.add(group[0])
                notify.send(admin, recipient=user, verb='恭喜您{}!,您的实名认证已通过审核!'.format(user.username))

            self.message_user(_("实名认证审核通过!"), 'success')

    @filter_hook
    def do_action(self, queryset):
        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission():
            raise PermissionDenied

        # Populate deletable_objects, a data structure of all related objects that
        # will also be deleted.

        if django_version > (2, 1):
            deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                queryset, self.opts, self.admin_site)
        else:
            using = router.db_for_write(self.model)
            deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                queryset, self.opts, self.user, self.admin_site, using)

        # The user has already confirmed the deletion.
        # Do the deletion and return a None to display the change list view again.
        if self.request.POST.get('post'):
            if perms_needed:
                raise PermissionDenied
            self.delete_models(queryset)
            # Return None to display the change list page again.
            return None

        if len(queryset) == 1:
            objects_name = force_text(self.opts.verbose_name)
        else:
            objects_name = force_text(self.opts.verbose_name_plural)

        if perms_needed or protected:
            title = _("Cannot delete %(name)s") % {"name": objects_name}
        else:
            title = _("Are you sure?")

        context = self.get_context()
        context.update({
            "title": title,
            "objects_name": objects_name,
            "deletable_objects": [deletable_objects],
            'queryset': queryset,
            "perms_lacking": perms_needed,
            "protected": protected,
            "opts": self.opts,
            "app_label": self.app_label,
            'action_checkbox_name': ACTION_CHECKBOX_NAME,
        })

        # Display the confirmation page
        return TemplateResponse(self.request, self.delete_selected_confirmation_template or
                                self.get_template_list('views/model_certification.html'), context)
